﻿using MongoDB.Bson;
using MongoDB.Driver;
using WebApplication1.Models;

namespace WebApplication1.Repository;

public class ChatMessageRepository
{
    private readonly IMongoCollection<ChatMessage> _collection;

    public ChatMessageRepository(IMongoDatabase database)
    {
        _collection = database.GetCollection<ChatMessage>("ChatMessages");
    }

    public async Task<List<ChatMessage>> GetAllAsync()
    {
        return await _collection.Find(_ => true).SortByDescending(m => m.Timestamp).ToListAsync();
    }
    public async Task<List<ChatMessage>> GetRecentMessagesAsync(int limit = 50)
    {
        return await _collection.Find(_ => true)
            .SortByDescending(m => m.Timestamp)
            .Limit(limit)
            .ToListAsync();
    }

    public async Task<List<ChatMessage>> GetByUserAsync(string user)
    {
        return await _collection.Find(m => m.FromUserId == user).SortByDescending(m => m.Timestamp).ToListAsync();
    }

    public async Task<List<ChatMessage>> GetPrivateMessagesAsync(string currentUser, string targetUser)
    {
        var filter = Builders<ChatMessage>.Filter.Or(
            Builders<ChatMessage>.Filter.And(
                Builders<ChatMessage>.Filter.Eq(m => m.FromUserId, currentUser),
                Builders<ChatMessage>.Filter.Eq(m => m.ToUserId, targetUser)
            ),
            Builders<ChatMessage>.Filter.And(
                Builders<ChatMessage>.Filter.Eq(m => m.FromUserId, targetUser),
                Builders<ChatMessage>.Filter.Eq(m => m.ToUserId, currentUser)
            )
        );

        return await _collection.Find(filter)
            .SortBy(m => m.Timestamp)
            .ToListAsync();
    }


}